package com.fly.mongodb.main;

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.Arrays;

public class QuickStartMongodb {
    /*
        1. 连接 mongodb 远程服务ip:port
        2. 获取数据库
        3. 获取数据集合
        4. 构造文档数据
        5. 插入文档
        6. 构造查询条件
        7. 查询指定集合
        8. 输出第一个查询到的文档
     */
    public static void main(String[] args) {
        String connectionString = "mongodb://192.168.199.144:27017";
        MongoClient mongoClient = MongoClients.create(connectionString);
        String databaseName = "productdb";
        MongoDatabase database = mongoClient.getDatabase(databaseName);

        String collectionName = "productdesc";
        MongoCollection<Document> collection = database.getCollection(collectionName);

        Document doc = new Document("name", "Mongodb")
                .append("type", "database")
                .append("count", 1)
                .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
                .append("info", new Document("x", 203).append("y", 102));

        collection.insertOne(doc);

        Bson eq = Filters.eq("name", "Mongodb");
        FindIterable<Document> documents = collection.find(eq);

        System.out.println(documents.first());

    }

    /*
        Document{{_id=6156bbc3f7dd4c380c064d36, name=Mongodb, type=database, count=1, versions=[v3.2, v3.0, v2.6], info=Document{{x=203, y=102}}}}
     */
}
